<template>
    <section class="form-container">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px" style="padding:30px 14px;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="分类" prop="articleTypeIdLevel">
                        <el-cascader
                            v-model="formData.articleTypeIdLevel"
                            :props="cascaderProps"
                            @change="handleChange"
                            clearable
                            style="width:100%;"
                            ref="cascaderRef"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="formData.title"/>
                    </el-form-item>
                    <el-form-item label="摘要" prop="summary">
                        <el-input type="textarea" v-model="formData.summary"/>
                    </el-form-item>
                </el-col>
                <el-col :span="1" style="min-height:1px;"></el-col>
                <el-col :span="11">
                    <el-form-item label="关键字" prop="keywords">
                        <el-input v-model="formData.keywords"/>
                        <div class="form-tips">以英文逗号分隔，每个关键字应控制在6个字以内.</div>
                    </el-form-item>
                    <el-form-item label="缩略图" prop="image">
                        <el-upload
                            class="avatar-uploader"
                            :action="apiHost + '/file/upload'"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            :headers="headers"
                        >
                            <div v-if="formData.thumbnail">
                                <img :src="formData.thumbnail" class="avatar">
                            </div>
                            <i v-else class="el-icon-plus avatar-uploader-icon"/>

                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="内容" prop="content">
                <editor
                    id="editor_id"
                    height="500px"
                    width="100%"
                    :content="formData.content"
                    :load-style-mode="false"
                    :upload-json="apiHost+'/file/upload'"
                    :headers="headers"
                    @on-content-change="onContentChange"
                />
            </el-form-item>

            <el-form-item>
                <el-popconfirm title="确定保存吗？" @onConfirm="submitForm()">
                    <el-button slot="reference" type="primary">保存</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>
    </section>
</template>

<script>
import {ArticleApi} from '@/api/cms/Article'
import {ArticleTypeApi} from '@/api/cms/ArticleType'
import {Common} from '@/utils/common'
import {getToken} from '@/utils/auth'

import editor from '@/components/Kindeditor/index.vue'

export default {
    name: 'CmsArticleUpdate',
    components: {editor},
    data() {
        return {
            formData: {
                id: 0,
                articleTypeId: 0,
                title: '',
                summary: '',
                keywords: '',
                thumbnail: '',
                content: '',
                articleTypeIdLevel: []
            },

            rules: {
                articleTypeIdLevel: [
                    {required: true, message: '请选择文章分类', trigger: 'change', type: 'array'}
                ],
                title: [
                    {required: true, message: '请输入文章标题', trigger: 'blur'},
                    {min: 1, max: 60, message: '长度在 1 到 60 个字符', trigger: 'blur'}
                ]
            },
            apiHost: process.env.VUE_APP_BASE_API,
            headers: {'X-Token': getToken()},
            cascaderProps: { //回显条件：默认数据赋值需放在this.$nextTick里且赋值后调用reloadCascader刷新组件
                lazy: true,
                value: 'id',
                label: 'articleTypeName',
                leaf:'leaf',
                lazyLoad(node, resolve) {
                    const {level, data} = node;
                    let parentId = level === 0 ? 0 : data.id
                    ArticleTypeApi.getListByParentId(parentId).then((response) => {
                        response.forEach(item=>{
                            item.leaf=!item.hasChildren
                        })
                        resolve(response);
                    })
                }
            }
        }
    },
    created() {
        this.showUpdate(this.$router.currentRoute.query.id)
    },
    methods: {
        // 显示组件
        showUpdate(id) {
            const that = this

            if (that.$refs['formRef'] !== undefined) {
                that.$refs['formRef'].resetFields()
            }

            that.$nextTick(() => {
                if (id > 0) {
                    that.getDetailById(id)
                } else {
                    that.formData.id = 0
                    that.formData.articleTypeId = 0
                    that.formData.articleTypeIdLevel = []
                }
            })
        },

        getDetailById(id){
            let that = this
            ArticleApi.getDetailById(id).then((response) => {
                that.formData = Common.assign(this.formData, response)

                let keywordArr = []
                response.keywordList.forEach(item => {
                    keywordArr.push(item.keyword)
                })

                that.formData.keywords = keywordArr.join(',')
                that.reloadCascader()
            })
        },

        handleSuccess(e) {
            this.formData.thumbnail = e.data
        },

        // 提交表单
        submitForm() {
            const that = this

            that.$refs['formRef'].validate((valid) => {
                if (valid) {
                    const submitData = Object.assign({}, that.formData)
                    submitData.articleTypeId = submitData.articleTypeIdLevel[submitData.articleTypeIdLevel.length - 1]
                    if (that.formData.id > 0) {
                        ArticleApi.edit(submitData).then(() => {
                            // 调用全局挂载的方法,关闭当前标签页
                            this.$store.dispatch('tagsView/delView', this.$route)
                            // 返回上一步路由，返回上一个标签页
                            this.$router.go(-1)
                        })
                    } else {
                        ArticleApi.add(submitData).then(() => {
                            // 调用全局挂载的方法,关闭当前标签页
                            this.$store.dispatch('tagsView/delView', this.$route)
                            // 返回上一步路由，返回上一个标签页
                            this.$router.go(-1)
                        })
                    }
                }
            })
        },
        onContentChange(val) {
            this.formData.content = val
        },
        handleChange(e) {
            this.formData.articleTypeId = e[e.length - 1]
        },
        reloadCascader() { //刷新组件，解决回显不生效问题
            let cs = this.$refs["cascaderRef"];
            cs.panel.activePath = [];
            cs.panel.loadCount = 0;
            cs.panel.lazyLoad();
        }
    }
}
</script>

<style>
</style>
